package com.deyuanyun.pic.pipe.controller.publiccontroller;

import com.deyuanyun.pic.common.util.FileUtils;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.PdfHelper;
import com.deyuanyun.pic.common.util.PdfUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.poi.ReadExcel;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by xu on 2016/1/15.
 */
@Controller
@RequestMapping("public/down/")
public class DownLoadController {
    static Logger logger=Logger.getLogger(DownLoadController.class);


    /**
     * 初始化excel的下载
     * @param response
     * @param fileName
     */
    public static void initExcelDownResponse(HttpServletResponse response,String fileName){

        String[] cnName=ReadExcel.cnNameMap.get(fileName);
        if (cnName!=null&&cnName.length>0&&StringUtils.isNotBlank(cnName[0])){
            HttpServletRequest request= RequestResponseContext.getRequest();
            String suff = FileUtils.getNameSuff(fileName);
            fileName= FileUtils.processFileName(request,cnName[0])+suff;
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+ StringUtils.replace(fileName,"/","-"));
    }

    /**
     * 输出excel
     * @param response
     */
    public static void excelOut(HttpServletResponse response,Workbook workbookFinal) {
        if (ObjectUtil.isEmptyAll(workbookFinal)){
            response.setHeader("Content-Disposition","");
            AjaxResponse.sendText(response,"<script>alert('数据为空，不可进行下载操作!');</script>");
           // AjaxResponse.sendText(response,"<script>alert('数据为空，不可进行下载操作!');javascript:history.back()</script>");
            return;
        }
        ServletOutputStream outputStream=null;
        try {
            outputStream = response.getOutputStream();
            workbookFinal.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            logger.error("",e);
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("",e);
                }
            }

        }
    }

    //下载穿跨越模板
    @RequestMapping("downCrossOverTemplate.json")
    @ResponseBody
    public void downCrossOverTemplate(HttpServletResponse response) throws Exception{
        String templateName="in/pipe_cross_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response, templateName);
        excelOut(response,workbook);
        return;
    }

    //下载地面标识模板
    @RequestMapping("downIdentificationTemplate.json")
    @ResponseBody
    public void downIdentificationTemplate(HttpServletResponse response) throws Exception{
        String templateName="in/identification_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    

    //下载定标点模板
    @RequestMapping("downTrackPointTemplate.json")
    @ResponseBody
    public void downTrackPointTemplate(HttpServletResponse response) throws Exception{
        String templateName="in/track_point_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }

    //下载收发球筒模板
    @RequestMapping("downPiggingstructureTemplate.json")
    @ResponseBody
    public void downPiggingstructure(HttpServletResponse response) throws Exception{
        String templateName="in/pigging_structure_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    
    @RequestMapping(value="celbow_t.json")
    @ResponseBody
    public void downExcelTemplate1(HttpServletResponse response) throws Exception{
        String templateName="in/celbow_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    @RequestMapping(value="elbow_t.json")
    @ResponseBody
    public void downExcelTemplate2(HttpServletResponse response) throws Exception{
        String templateName="in/elbow_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    @RequestMapping(value="pipe_segment_gis.json")
    @ResponseBody
    public void downExcelTemplate3(HttpServletResponse response) throws Exception{
        String templateName="in/pipe_segment_gis_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    @RequestMapping(value="tee_t.json")
    @ResponseBody
    public void downExcelTemplate4(HttpServletResponse response) throws Exception{
        String templateName="in/tee_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    @RequestMapping(value="valve_room_t.json")
    @ResponseBody
    public void downExcelTemplate5(HttpServletResponse response) throws Exception{
        String templateName="in/valve_room_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    @RequestMapping(value="valve_t.json")
    @ResponseBody
    public void downExcelTemplate6(HttpServletResponse response) throws Exception{
        String templateName="in/valve_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    @RequestMapping(value="pipe_segment_t.json")
    @ResponseBody
    public void downExcelTemplate7(HttpServletResponse response) throws Exception{
        String templateName="in/pipe_segment_t.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }
    
    /**
     * 下载用户模板
     * @author tt
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="downExcelUserTemplate.json")
    @ResponseBody
    public void downExcelUserTemplate(HttpServletResponse response) throws Exception{
    	String templateName="in/user_in_templet.xls";
        Workbook workbook= ReadExcel.readExcelTemplate(templateName);
        initExcelDownResponse(response,templateName);
        excelOut(response,workbook);
        return;
    }

    /**
     * 下载导入excel时 的错误信息
     * @param response
     * @param html
     * @throws Exception
     */
    @RequestMapping(value="downExcelMessage.json")
    @ResponseBody
    public void downExcelMessage(HttpServletResponse response,String html){
        /*html=StringUtils.replaceEach(html,new String[]{"<br>","</br>","<p>","</p>","<div>","</div>","<span>","</span>",">>",">>>","&gt;"}
                ,new String[]{"<br/>","<br/>","","","","","","","","",""});*/
        //html= StringEscapeUtils.escapeHtml(html);
        String reg="<[^br>]+>";
        Pattern p_html = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
        if (StringUtils.isBlank(html)){
            response.setHeader("Content-Disposition","");
            AjaxResponse.sendText(response,"<script>alert('数据为空，不可进行下载操作!');</script>");
            return;
        }
        Matcher m_html = p_html.matcher(html);
        if (m_html!=null){
            html = m_html.replaceAll(""); // 过滤html标签
        }

        html=StringUtils.replace(html,"<br>","<br/>");

        Map<String, Object> o=new HashMap<String, Object>();
        o.put("message",html);

        OutputStream os = null;
        String realPath= PdfHelper.getPath();
        try {
            os= PdfUtils.generateToServletOutputStream(realPath, "pdfFile/downErr.ftl", null, o, response);
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=dataErr.pdf" );
            byte[] buffer = new byte[1024];
            os.write(buffer);// 输出文件
            os.flush();
        } catch (Exception e) {
            logger.error("",e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
